<template>
  <div class="main-container container-limited container-fluid page-holder">
    <div class="page-title-holder no-border-bottom">
      <h2 class="page-title">创建资源</h2>
    </div>
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item prop="title" ref="title">
        <el-input v-model="form.title" placeholder="请输入标题" />
        <span class="draft-msg body-line-height f-mini">
          {{ draftBox.msg }}
          <timeago
            :date-time="draftBox.saveTime"
            enable-type="realTime"
            :time-format="['date', 'time', 'seconds']"
            pre-text="("
            post-text=")"
          />
        </span>
      </el-form-item>
      <el-form-item prop="content" ref="content">
        <tinymce-editor v-if="draftBox.enable" v-model="form.content" :height="550" />
<!--        <el-input v-show="false" v-model="form.content" />-->
<!--        <ckeditor-->
<!--          v-if="draftBox.enable"-->
<!--          :initial-content="form.content"-->
<!--          :content.sync="form.content"-->
<!--          class="h-normal"-->
<!--        />-->
      </el-form-item>
      <el-form-item prop="folder" ref="folder">
        <el-input v-show="false" :v-model="form.folder" />
        <div class="flex align-items-center">
          <div class="info text-right sub-label shrink-0 m-r-16">所属目录</div>
          <el-button
            size="small"
            v-text="form.folder || '选择目录'"
            @click="selectFolderDialogVisible = true"
          />
          <select-folder-dialog
            :dialog-visible.sync="selectFolderDialogVisible"
            :selected-folder-id.sync="form.selectedFolderId"
            :selected-folder-path.sync="form.folder"
            :space-id="Number($route.params.spaceId)"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <tag-select :selected-tags.sync="form.tags" />
      </el-form-item>
      <el-form-item prop="attaches" ref="attaches">
        <div class="flex">
          <div class="info text-right sub-label shrink-0 m-r-16">资源附件</div>
          <upload-attaches :attaches.sync="form.attaches" class="flex-1" />
        </div>
      </el-form-item>
      <el-form-item v-if="isWebAdmin || isSpaceOwner || isSpaceAdmin">
        <el-collapse v-model="activeName">
          <el-collapse-item :name="1">
            <div slot="title" class="info text-right sub-label shrink-0 m-r-16">更多选项</div>
            <div class="flex align-items-center m-t-16">
              <div class="sub-label shrink-0 m-r-16"></div>
              <el-checkbox v-model="form.good">精品资源</el-checkbox>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :loading="loading">提交</el-button>
        <el-button class="float-right" @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex';
import TagSelect from '@/components/shared/TagSelect';
import UploadAttaches from '@/components/shared/UploadAttaches';
import SelectFolderDialog from '@/components/shared/select-folder-dialog';

export default {
  name: 'DocCreate', // 创建资源
  components: { TagSelect, UploadAttaches, SelectFolderDialog },
  data() {
    return {
      form: {
        title: '',
        content: '',
        tags: [],
        attaches: [],
        selectedFolderId: undefined, // 资源目录
        folder: '',
        good: false, // 是否为精品资源
      },
      rules: {
        title: [{ required: true, validator: this.$va.title }],
        content: [{ required: true, validator: this.$va.content }],
        folder: [{ required: true, message: '请选择资源存放的目录' }],
        attaches: [{ validator: this.$va.attaches, trigger: 'none' }],
      },
      draftBox: {
        enable: false, // 是否启用草稿箱（当正常加载草稿内容后再启用）
        saveTime: '', // 草稿保存的时间
        msg: '', // 提示信息
      },
      timer: null, // 草稿箱计时器（包裹在draftBox内会导致无法清除）
      selectFolderDialogVisible: false,
      loading: false, // 创建资源
      activeName: 1,
    };
  },
  computed: {
    ...mapState({
      curUser: 'currentUser',
      curSpace: 'currentSpace',
      curFolder: 'currentFolder',
    }),
    ...mapGetters(['isWebAdmin', 'isSpaceOwner', 'isSpaceAdmin']),
    // 草稿箱（监听所需参数）
    draft() {
      const attaches = this.form.attaches.filter(attach => attach.status === 'success'); // 只保存已上传完成的附件
      const { title, content, tags } = this.form;
      return { title, content, tags, attaches };
    },
    draftName() {
      const nameBase = 'learnerhub-draft-resource-create';
      return {
        title: `${nameBase}-title-user-${this.curUser.id}-space-${this.curSpace.id}`,
        content: `${nameBase}-content-user-${this.curUser.id}-space-${this.curSpace.id}`,
        tags: `${nameBase}-tags-user-${this.curUser.id}-space-${this.curSpace.id}`,
        attaches: `${nameBase}-attaches-user-${this.curUser.id}-space-${this.curSpace.id}`,
      };
    },
    createParams() {
      return {
        spaceId: this.curSpace.id,
        title: this.form.title, // 默认将资源标题作为贡献标题
        resources: [ // 按照api组装，后续不再重组
          {
            class_type: 'ProductSnippet', // 类型为文档
            title: this.form.title, // 资源标题
            content: this.form.content, // 资源内容
            tag_titles: this.form.tags, // 资源标签
            parent_id: this.form.selectedFolderId || undefined, // 资源父id
            is_good: this.form.good, // 是否精品资源
          },
          ...this.form.attaches.map(attach => ({
            class_type: 'ProductDocument',
            title: attach.name,
            ufile_key: attach.response.key,
            ufile_size: attach.size,
          })),
        ],
      };
    },
  },
  mounted() {
    this.takeFromDraft();
    this.initCurrentFolder();
  },
  methods: {
    ...mapActions({
      setCurFolder: 'setCurrentFolder',
    }),
    onSubmit() {
      this.$refs.form.validate((valid, errs) => {
        if (valid) {
          this.loading = true;
          this.$api.spaceContributions.create(this.createParams)
            .then((res) => {
              this.$root.$emit('loadSidebarItemsCount');
              this.$message.success('提交成功');
              this.clearDraft();
              this.setCurFolder();
              if (this.curSpace.autoAccept || this.isSpaceOwner || this.isSpaceAdmin) {
                this.$router.push(`/spaces/${this.curSpace.id}/resources-docs/${res.data.product_file_id}`);
              } else this.$router.push(`/spaces/${this.curSpace.id}/contributions/${res.data.id}`);
            })
            .catch(() => {})
            .then(() => { this.loading = false; });
        } else this.$refs[Object.keys(errs)[0]].$el.scrollIntoView({ block: 'center' });
      });
    },
    // 当前目录
    initCurrentFolder() {
      this.form.selectedFolderId = this.curFolder.id;
      this.form.folder = this.curFolder.displayPath;
    },
    // 从草稿箱拿东西
    takeFromDraft() {
      this.form.title = localStorage.getItem(this.draftName.title) || '';
      this.form.content = localStorage.getItem(this.draftName.content) || '';
      this.form.tags = JSON.parse(localStorage.getItem(this.draftName.tags)) || [];
      this.form.attaches = JSON.parse(localStorage.getItem(this.draftName.attaches)) || [];
      const { title, content, tags, attaches } = this.form;
      if (title || content || tags.length || attaches.length) {
        this.draftBox.msg = '已加载上次的草稿';
      }
      this.$nextTick(() => { this.draftBox.enable = true; }); // 草稿箱开始计时
    },
    // 清空 storage 中的草稿箱
    clearDraft() {
      localStorage.removeItem(this.draftName.title);
      localStorage.removeItem(this.draftName.content);
      localStorage.removeItem(this.draftName.tags);
      localStorage.removeItem(this.draftName.attaches);
    },
  },
  watch: {
    draft() { // 草稿自动保存
      if (!this.draftBox.enable) return; // 未启用
      if (this.timer) clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        localStorage.setItem(this.draftName.title, this.draft.title);
        localStorage.setItem(this.draftName.content, this.draft.content);
        localStorage.setItem(this.draftName.tags, JSON.stringify(this.draft.tags));
        localStorage.setItem(this.draftName.attaches, JSON.stringify(this.draft.attaches));
        this.draftBox.saveTime = new Date().toString();
        this.draftBox.msg = '草稿已自动保存';
      }, 1000);
    },
  },
};
</script>

<style></style>
